﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPortTool
{
    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            this.serialControl1.ReceiveDataEnd += SerialControl1_ReceiveDataEnd;
            this.serialControl2.ReceiveDataEnd += SerialControl2_ReceiveDataEnd;
        }
        private void SerialControl1_ReceiveDataEnd(object obj, Quick.Communicator.SerialPortEventArgs e)
        {
            try
            {
                if (isTransfer)
                {
                    bool bl = serialControl2.SendData(e.DatagramByte);
                    if (isWriteLog)
                    {
                        Utility.Log.Log4net.Instance["logSystemInfo"].Info($"[1]收到数据:{ Utility.Byte.HexString.ByteToHexString(e.DatagramByte)} \r\n发送[2]结果:{bl.ToString()}");
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.Log.Log4net.Instance["logSystemInfo"].Error("1发2异常", ex);
            }
        }
        private void SerialControl2_ReceiveDataEnd(object obj, Quick.Communicator.SerialPortEventArgs e)
        {
            try
            {
                if (isTransfer)
                {
                    bool bl = serialControl1.SendData(e.DatagramByte);
                    if (isWriteLog)
                    {
                        Utility.Log.Log4net.Instance["logSystemInfo"].Info($"[2]收到数据:{ Utility.Byte.HexString.ByteToHexString(e.DatagramByte)} \r\n发送[1]结果:{bl.ToString()}");
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.Log.Log4net.Instance["logSystemInfo"].Error("2发1异常", ex);
            }
        }

        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                serialControl1.Stop();
                serialControl2.Stop();
            }
            catch (Exception ex)
            {
                Utility.Log.Log4net.Instance["logSystemInfo"].Error("窗口关闭异常", ex);
            }
        }
        bool isWriteLog = true;
        private void chkLog_CheckedChanged(object sender, EventArgs e)
        {
            isWriteLog = chkLog.Checked;
        }
        bool isTransfer = true;
        private void chkTransfer_CheckedChanged(object sender, EventArgs e)
        {
            isTransfer = chkTransfer.Checked;
        }
    }
}
